<template>
  <view class="mobile-item-container">
    <Navbar title="重要客户" bgColor="#fff" :h5Show="false" :autoBack="true" :border="true" :onListshow="true"
            @searchList="searchList" @operate="operate" :showCheckboxes="showCheckboxes" :fixed="true"></Navbar>
    <u-sticky>
      <view v-if="showCheckboxes">
        <u-row justify="space-between" customStyle="margin-bottom: 8px">
          <u-col span="3">
          </u-col>
          <u-col span="7">
            <view style="color: #1b64edb5; display:flex ;">
              <u-button type="primary" size="small" text="跟进记录" style="width: 60px;" @click="handleFollowUp"></u-button>
              <u-button type="primary" size="small" text="放入公海" color="#2fbe25" style="width: 60px;"
                        @click="handlePublicPool"></u-button>
            </view>
          </u-col>
        </u-row>
      </view>
    </u-sticky>
    <view style="width: 100%; border-bottom:1px solid #dbdcdf ; margin: 3vh 0vh; font-size: 15px;"
          v-for="(item, index) in customersList" :key="index">
      <u-row customStyle="margin-bottom: 10px">
        <u-col v-if="showCheckboxes" :span="showCheckboxes ? 1 : 0">
          <u-checkbox :value="item.id" @change="checkboxChange(item.id)"></u-checkbox>
        </u-col>
        <u-col :span="showCheckboxes ? 11 : 12">
          <view class="demo-layout bg-purple"></view>
          <u-row customStyle="margin-bottom: 5px">
            <u-col span="4">
              <view>线索名称：</view>
            </u-col>
            <u-col span="8">
              <view style="display: flex;">
                {{ item.name }}
                <!-- <u-icon name="phone-fill" size="20" color="#1b64edb5" style="margin-left: 20px;"
                        @click="handleCallDial(item)"></u-icon>
                <u-icon name="man-add-fill" size="20" color="#1b64edb5" style="margin-left: 10px;"
                        @click="handleAddWx(item)"></u-icon> -->
              </view>
            </u-col>
          </u-row>
          <u-row customStyle="margin-bottom: 5px">
            <u-col span="4">
              <view>城市：</view>
            </u-col>
            <u-col span="8">
              <view> {{ item.city }}</view>
            </u-col>
          </u-row>
          <u-row customStyle="margin-bottom: 5px">
            <u-col span="4">
              <view>跟进人：</view>
            </u-col>
            <u-col span="8">
              <view> {{ item.username }}</view>
            </u-col>
          </u-row>
          <u-row customStyle="margin-bottom: 3px">
            <u-col span="4">
              <view>申请时间：</view>
            </u-col>
            <u-col span="8">
              <view>{{ item.createTime }}</view>
            </u-col>
          </u-row>
          <u-row justify="space-between" customStyle="margin-bottom: 8px">
            <u-col span="3">
            </u-col>
            <u-col span="2" @click="handelDetails(item)">
              <view style="color: #1b64edb5;">更多 ></view>
            </u-col>
          </u-row>
        </u-col>
      </u-row>
    </view>
    <u-loadmore :status="loadmoreStatus" />
    <u-popup :show="show" @close="close()" @open="open" mode="right" closeable>
      <view style="padding: 20px;">筛选条件</view>
      <view style="padding: 20px;">
        <u-form labelPosition="left" :model="queryParams" ref="uForm" labelWidth="80">
          <u-form-item label="客户信息" prop="search" ref="search">
            <u--input v-model="queryParams.search" placeholder="请输入内容"></u--input>
          </u-form-item>
          <u-form-item label="城市" prop="city" ref="city">
            <u--input v-model="queryParams.city" placeholder="请输入内容"></u--input>
          </u-form-item>
          <u-form-item label="线索ID" prop="id" ref="id">
            <u--input v-model="queryParams.id" placeholder="请输入内容"></u--input>
          </u-form-item>
          <u-form-item label="客户类型" @click="showPicker = true" prop="statusLabel">
            <u-input readonly v-model="queryParams.statusLabel" placeholder="请选择"
                     style="pointer-events:none; width: 100%;" />
          </u-form-item>
        </u-form>
      </view>
      <u-button type="primary" text="查询" style="width: 80%;" @click="getList()"></u-button>
      <u-button text="重置" style="width: 80%;" @click="reset()"></u-button>
    </u-popup>

    <u-picker :show="showCard" :columns="columnsCard" keyName="label" @cancel="showCard = false"
              @confirm="handleConfirmCard"></u-picker>


    <u-modal :show="showModal" :title="title" @cancel=" showModal = false" :showCancelButton="true" cancelText="取消"
             @confirm="handleConfirmWx">
      <view class="slot-content">
        <u--form labelPosition="left" :model="wxForm" :rules="wxRules" ref="wxuForm" labelWidth="100">
          <u-form-item label="验证信息" prop="vinfo" borderBottom ref="vinfo" required>
            <u--input v-model="wxForm.vinfo" border="none" placeholder="请输入验证信息"></u--input>
          </u-form-item>
          <u-form-item label="备注" prop="note" borderBottom ref="note" style="padding-top: 10px">
            <u--input v-model="wxForm.note" border="none" placeholder="请输入备注"></u--input>
          </u-form-item>
        </u--form>
      </view>
    </u-modal>
    <u-modal :show="showConfirmModal" title="确认操作" :content="content" showCancelButton cancelText="取消" confirmText="确定"
             @confirm="confirmMoveToPublicPool" @cancel="showConfirmModal = false"></u-modal>
    <view class="wrap">
      <u-back-top :scrollTop="scrollTop" :mode="mode" :iconStyle="iconStyle"></u-back-top>
    </view>
    <!-- 填写跟进记录弹出层 -->
    <u-popup :show="showFollowUp" @close=" showFollowUp = false" mode="right" closeable>
      <view style="padding: 20px;">
        <u-form labelPosition="left" :model="followUpForm" ref="followUpForm" labelWidth="80" :rules="followUpRules">
          <u-form-item label="客户星级" @click="handleStarPicker" prop="starLabel" required>
            <u-input readonly v-model="followUpForm.starLabel" placeholder="请选择"
                     style="pointer-events:none; width: 100%;" />
          </u-form-item>
          <u-form-item label="跟进状态" @click="handlePicker()" prop="statusLabel" required>
            <u-input readonly v-model="followUpForm.statusLabel" placeholder="请选择"
                     style="pointer-events:none; width: 100%;" />
          </u-form-item>
          <u-form-item label="跟进内容" prop="followRemark" ref="followRemark" required>
            <u-textarea v-model="followUpForm.followRemark" placeholder="请输入跟进内容" count height="130" maxlength="1000"
                        confirm-type="send"></u-textarea>
          </u-form-item>

          <view v-if="paymentForm">
            <u-form-item label="回款金额" prop="amount" required>
              <u--input v-model="followUpForm.amount" placeholder="请输入回单金额"></u--input>
            </u-form-item>
            <u-form-item label="回款日期" prop="collectionDate" @click="handleCollectionDate" required>
              <u-input v-model="followUpForm.collectionDate" placeholder="请选择回款日期" readonly
                       style="pointer-events:none; width: 100%;" />
            </u-form-item>
            <u-form-item label="回款方式" prop="paymentCollectionMethodLabel" @click="handlePayment" required>
              <u-input v-model="followUpForm.paymentCollectionMethodLabel" placeholder="请选择回款方式" readonly
                       style="pointer-events:none; width: 100%;" />
            </u-form-item>
            <u-form-item label="放款金额" prop="realAmount">
              <u--input v-model="followUpForm.realAmount" placeholder="请输入放款金额"></u--input>
            </u-form-item>
          </view>
          <u-datetime-picker :show="showCollectionDate" v-model="CollectionDateValue" mode="date"
                             @confirm="submitCollectionDate"></u-datetime-picker>
        </u-form>
      </view>
      <u-button type="primary" text="提交" style="width: 80%;" @click="submitFollowUp"></u-button>
    </u-popup>
    <u-picker :show="showPicker" :columns="columnsPicker" keyName="label" @confirm="nationSel"
              @cancel="showPicker = false" @close="showPicker = false"></u-picker>
    <u-picker :show="showStarPicker" :columns="columnsStarPicker" keyName="label" @confirm="starSel"
              @cancel="showStarPicker = false" @close="showStarPicker = false"></u-picker>
    <!-- 回款方式 -->
    <u-picker :show="showPayment" :columns="columnsPayment" keyName="label" @confirm="submitPayment"
              @cancel="showPayment = false" @close="showPayment = false"></u-picker>
  </view>
</template>
<script>
import Navbar from '@/components/navbar/Navbar'
import {
  getImportantList, currentDial, currentQuery, addFriend, movetoPublicPool,
  movetoImportant, dictionaries, putCustomers, getCustomers, getCollectionMethod,
  postPayment
} from '@/api/api'
import moment from 'moment'
export default {
  components: {
    Navbar,
  },
  data() {
    return {
      scrollTop: 0,
      mode: 'square',
      iconStyle: {
        fontSize: '32rpx',
        color: '#2979ff'
      },
      activeKey: 'unread',
      tabs: [{
        name: '未跟进',
        key: 'unread',
        badge: {
          value: 2,
        }
      }, {
        name: '已跟进',
        key: 'read'
      }, {
        name: '全部',
        key: 'all'
      }],
      params: {
        pageNum: 0,
        pageSize: 10
      },
      list: [],
      activeStyle: {
        color: '#303133',
        fontSize: '20px',
        fontWeight: 'bold',
        transform: 'scale(1.05)'
      },
      show: false,
      model: {
        name: '',
        city: '',
        id: '',
        type: ''
      },
      showPicker: false,
      showStarPicker: false,
      showCard: false,
      columnsCard: [
        [{
          label: '卡1',
          id: 1,
        }, {
          label: '卡2',
          id: 2
        }]
      ],
      queryParams: {
        page: 1,
        size: 10,
      },
      customersList: [],
      showCheckboxes: false, // 控制是否显示复选框
      selectedItems: [], // 存储选中的项
      loadmoreStatus: 'loadmore',
      columnsPicker: [],
      columnsStarPicker: [],
      phone: false,
      phone2: false,
      customersObj: {},
      showModal: false, // 控制模态框的显示
      title: '', // 模态框标题
      wxForm: {
        vinfo: '',
        note: '',
      },
      wxRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: ['blur', 'change'] }
        ]
      },
      showConfirmModal: false,
      checkId: [], // 存储选中项的 ID
      content: '',
      modalType: '',
      statusList: [],
      starList: [],
      showFollowUp: false, // 控制跟进记录弹出层的显示
      followUpForm: {
        status: '',
        statusLabel: '',
        followRemark: '',
        starLabel: '',
        starStatus: '',
      },
      followUpRules: {
        status: [
          { required: true, message: '请选择跟进状态', trigger: ['blur', 'change'] }
        ],
        followRemark: [
          { required: true, message: '请输入跟进信息', trigger: ['blur', 'change'] }
        ],
        starStatus: [
          { required: true, message: '请选择客户星级', trigger: ['blur', 'change'] }
        ],
        amount: [
          { required: true, message: '请输入回款金额', trigger: ['blur', 'change'] }
        ],
        collectionDate: [
          { required: true, message: '请输入回款日期', trigger: ['blur', 'change'] }
        ],
        paymentCollectionMethodLabel: [
          { required: true, message: '请输入回款方式', trigger: ['blur', 'change'] }
        ],
      },
      detailsList: {},
      showCollectionDate: false,
      CollectionDateValue: Number(new Date()),
      showPayment: false,
      columnsPayment: [],
      paymentForm: false,
      statusType: null,
    }
  },
  created() {
    // this.loadData()
    this.getList(1)
    this.getDictionaries()
  },

  onReachBottom() {
    if (this.loadmoreStatus === 'nomore') return;
    this.loadmoreStatus = 'loading';
    this.queryParams.page++;
    this.getList(2); // 自动加载下一页数据
  },

  onPullDownRefresh() {
    // 重置分页参数
    this.queryParams.page = 1;
    this.loadmoreStatus = 'loadmore';

    // 请求第一页数据
    this.getList(1).finally(() => {
      uni.stopPullDownRefresh(); // 停止下拉刷新动画
    });
  },

  onPageScroll(e) {
    this.scrollTop = e.scrollTop;
  },

  methods: {

    handlePayment() {
      this.showPayment = true
      this.showStarPicker = false
      this.showPicker = false
      this.showCollectionDate = false
    },

    submitPayment(tagVal) {
      this.followUpForm.paymentCollectionMethodLabel = tagVal.value[0].label
      this.followUpForm.paymentCollectionMethod = tagVal.value[0].value
      this.showPayment = false
    },

    // 时间选择
    submitCollectionDate(tagVal) {
      this.followUpForm.collectionDate = moment(tagVal.value).format('YYYY-MM-DD');
      this.showCollectionDate = false
    },

    // 点击出现时间选择框
    handleCollectionDate() {
      this.showStarPicker = false
      this.showPicker = false
      this.showPayment = false
      this.showCollectionDate = true
    },

    handleStarPicker() {
      this.showStarPicker = true
      this.showPicker = false
      this.showCollectionDate = false
      this.showPayment = false
    },

    handlePicker() {

      this.showStarPicker = false
      this.showCollectionDate = false
      this.showPayment = false
      if (this.detailsList.status == 600) {
        this.showPicker = false
      } else {
        this.showPicker = true
      }

    },

    handelDetails(item) {
      uni.navigateTo({
        url: `/pages/crm/detailsList?id=${item.id}`
      })
    },

    //填写跟进记录
    handleFollowUp() {
      this.paymentForm = false
      if (this.checkId.length == 1) {
        this.showFollowUp = true
        this.getCustomers()
      } else {
        uni.showToast({
          title: '请选择一条数据填写跟进记录',
          icon: 'none'
        });
      }
    },
    getCustomers() {
      getCustomers(this.checkId[0]).then(res => {
        if (res.code == 200) {
          this.detailsList = res.data
          this.followUpForm = {
            status: res.data.status,
            starStatus: res.data.starStatus,
            // statusLabel: res.data.statusLabel,
          };
          this.columnsPicker.map(item => {
            item.map(value => {
              if (value.value == res.data.status) {
                this.followUpForm.statusLabel = value.label
              }
            })
          })
          this.columnsStarPicker.map(item => {
            item.map(value => {
              if (value.value == res.data.starStatus) {
                this.followUpForm.starLabel = value.label
              }
            })
          })

          if (res.data.status == 600) {
            this.paymentForm = true
          }
        }
      })
    },

    // 跟进记录确定

    submitFollowUp() {
      let A = {}
      this.$refs.followUpForm.validate().then((valid) => {
        if (valid) {
          // 将 detailsList 和 followUpForm 合并到 A 中
          A = {
            ...this.detailsList,
            ...this.followUpForm
          };

          // 调用接口提交数据
          putCustomers(A).then((res) => {
            if (res.code === 200) {
              uni.showToast({
                title: '跟进记录提交成功',
                icon: 'none'
              });
              // 提交成功后可做一些后续操作，如关闭弹窗
              this.showFollowUp = false;
              // this.checkId = []; // 清空选中项的 ID 数组
              // this.showCheckboxes = false; // 隐藏复选框
            } else {
              uni.showToast({
                title: '跟进记录提交失败',
                icon: 'none'
              });
            }
          })

          if (this.paymentForm) {
            A.customerId = A.id

            postPayment(A).then(res => {
              if (res.code == 200) {
                uni.showToast({
                  title: '回款记录提交成功',
                  icon: 'none'
                });
                // 提交成功后可做一些后续操作，如关闭弹窗
                this.showFollowUp = false;
                this.checkId = []; // 清空选中项的 ID 数组
                this.showCheckboxes = false; // 隐藏复选框
              } else {
                uni.showToast({
                  title: '回款记录提交失败',
                  icon: 'none'
                });
              }
            })

          }

          //
        }
      });
    },


    // 获取字典
    async getDictionaries() {
      const res = await dictionaries()
      if (res.code == 200) {
        this.columnsPicker = [res.data.statusList]
        this.columnsStarPicker = [res.data.starList]
      }
      const collectionMethod = await getCollectionMethod()
      if (collectionMethod.code == 200) {
        this.columnsPayment = [collectionMethod.data]
      }
    },

    // 加入重要客户
    handleImport() {
      this.content = '确定要将选中的客户放入重要客户吗？';
      this.showConfirmModal = true;
      this.modalType = 'import'

    },

    // 放入公海
    handlePublicPool() {
      // 显示确认模态框
      this.content = '确定要将选中的客户放入公海吗？';
      this.showConfirmModal = true;
      this.modalType = 'public'

    },
    confirmMoveToPublicPool() {
      if (this.modalType == 'public') {
        movetoPublicPool(this.checkId).then(res => {
          if (res.code == 200) {
            uni.showToast({
              title: '放入公海成功',
              icon: 'none'
            });
            // // 清空选中状态
            this.checkId = []; // 清空选中项的 ID 数组
            this.selectedItems = []; // 清空已选中的项
            this.showCheckboxes = false; // 隐藏复选框
            this.showConfirmModal = false;
            // 刷新列表
            setTimeout(() => {
              this.getList(1);
            }, 1000);

          } else {
            uni.showToast({
              title: '放入公海失败',
              icon: 'none'
            });
          }
        })
      } else if (this.modalType == 'import') {
        movetoImportant(this.checkId).then(res => {
          if (res.code == 200) {
            uni.showToast({
              title: '放入重要客户成功',
              icon: 'none'
            });
            // // 清空选中状态
            this.checkId = []; // 清空选中项的 ID 数组
            this.selectedItems = []; // 清空已选中的项
            this.showCheckboxes = false; // 隐藏复选框
            this.showConfirmModal = false;
            // 刷新列表
            setTimeout(() => {
              this.getList(1);
            }, 1000);

          } else {
            uni.showToast({
              title: '放入重要客户失败',
              icon: 'none'
            });
          }
        })


      }
      // 调用放入公海接口

    },

    // 微信确定按钮
    handleConfirmWx() {
      this.$refs.wxuForm.validate().then(valid => {
        if (valid) {
          addFriend({
            cusId: this.customersObj.id, ...this.wxForm
          }).then(res => {
            if (res.code == 200) {
              const msg = JSON.parse(res.msg).message
              uni.showToast({
                title: msg,
                icon: 'none'
              });
            } else {
              uni.showToast({
                title: '添加失败',
                icon: 'none'
              });
            }
          })
          this.showModal = true;
          this.customersObj = {}
          this.wxForm = {}
        }

      })
    },


    // 点击添加微信
    handleAddWx(item) {
      this.showModal = true; // 显示模态框
      this.title = '添加微信'; // 设置模态框标题
      this.customersObj = item
    },


    // 点击拨打电话
    async handleCallDial(item) {
      this.showCard = true
      const getPhone = await currentQuery()
      this.phone = getPhone.data ? getPhone.data.phone ? false : true : true
      this.phone2 = getPhone.data ? getPhone.data.phone2 ? false : true : true
      this.customersObj = item
    },

    // 选择值确定
    handleConfirmCard(item) {
      if (item.value[0].id == 1) {
        if (this.phone) {
          uni.showToast({
            title: '请先安装卡1',
            icon: 'none'
          });
          return
        }
        this.showCard = false;
      } else {
        if (this.phone2) {
          uni.showToast({
            title: '请先安装卡2',
            icon: 'none'
          });
          return
        }
        this.showCard = false;
      }
      this.currentDial(item.value[0].id)
      // 隐藏选择器
    },

    // 拨打电话调用接口
    currentDial(type) {
      // customersObj
      currentDial({
        cusId: this.customersObj.id, cardSlotNum: type
      }).then(res => {
        if (res.code == 200) {
          const msg = JSON.parse(res.msg).message
          uni.showToast({
            title: msg,
            icon: 'none'
          });
        } else {
          uni.showToast({
            title: '拨打失败',
            icon: 'none'
          });

        }

      })
    },



    reset() {
      this.queryParams = {
        page: 1,
        size: 10,
      }
      this.getList(1)
    },

    checkboxChange(id) {
      const index = this.checkId.indexOf(id);
      if (index === -1) {
        // 若 ID 不在数组中，添加该 ID
        this.checkId.push(id);
      } else {
        // 若 ID 已存在，从数组中删除
        this.checkId.splice(index, 1);
      }


    },

    // 操作按钮
    operate() {
      this.showCheckboxes = !this.showCheckboxes;
      if (!this.showCheckboxes) {
        this.selectedItems = []; // 清空已选中的项
      }
    },

    // 获取列表信息
    async getList(reset) {
      try {
        const res = await getImportantList(this.queryParams);
        if (res.code === 200) {
          this.show = false;
          if (this.queryParams.page === 1) {
            // 下拉刷新或首次加载：清空列表并替换为新数据
            this.customersList = res.data.records;
          } else {
            // 上拉加载：追加数据
            this.customersList = reset === 2
                ? [...this.customersList, ...res.data.records]
                : res.data.records;
          }
          // 更新加载状态
          this.loadmoreStatus = res.data.records.length < this.queryParams.size
              ? 'nomore'
              : 'loadmore';
          console.log('数据加载成功', this.customersList);
          return res;
        } else {
          console.error('请求返回非 200 状态码', res);
          uni.showToast({
            title: '获取数据失败',
            icon: 'none'
          });
          throw new Error('请求失败');
        }
      } catch (err) {
        console.error('请求出错', err);
        uni.showToast({
          title: '网络请求出错',
          icon: 'none'
        });
        this.loadmoreStatus = 'error'; // 设置加载状态为错误
        throw err;
      }
    },

    nationSel(event) {
      this.paymentForm = false
      let value = event.value
      this.queryParams.statusLabel = value[0].label;
      this.queryParams.status = value[0].value;
      this.followUpForm.statusLabel = value[0].label;
      this.followUpForm.status = value[0].value;
      this.showPicker = false;

      if (value[0].value == 600) {
        this.paymentForm = true
      }


    },

    starSel(event) {
      let value = event.value
      this.followUpForm.starStatus = value[0].value;
      this.followUpForm.starLabel = value[0].label;
      this.showStarPicker = false;
    },

    searchList() {
      //
      this.show = true
    },
    close() {
      this.show = false
    },
    open() {
      this.show = true
    },
    // 加载通知公告数据
    loadData() {
      // const app = this
      // this.params.pageNum += 1;
      // NoticeApi.noticeList(this.params).then(res => {
      //   app.list = res.rows;
      // })
    },
    tabChange(item) {
      this.activeKey = item.key;
      this.params.pageNum = 0;
      // this.loadData();
    },
    // 滚动分页加载数据
    scrolltolower() {
      this.loadData();
    },
    toDetail(notice) {
      uni.navigateTo({ url: '/pages/work/notice/detail?id=' + notice.noticeId })
    },
    goBack() {
      alert(111)
      console.log('goBack');
      uni.navigateBack({
        delta: 1, // 返回上一级页面
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.notice-item-tips {
  border-radius: 8px;
  background-color: #f4f4f5;
  padding: 9px 16px;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  align-items: center;
}

.button-group {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.wrap {
  // height: 200vh;
}
</style>